﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web.Hosting;

namespace FileUploader.Web {
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "FileUploaderService" in code, svc and config file together.
    public class FileUploaderService : IFileUploaderService {
        private static string filename;

        public FileUploaderService(){
        }

        public List<string> GetFilesOnServer(){

            string path = getDataPath();
            DirectoryInfo directory = new DirectoryInfo(path);
            return directory.GetFiles().Select(fi => fi.Name).ToList();
        }

        
        public void SendFile(Stream stream){
            Debug.WriteLine("SendFile");
            Trace.WriteLine("SendFile");
//                using (FileStream fs = File.Create(filename)) {
                    //SaveFile(stream, fs);
//                }
                return ;
        }

        public void SetFileName(string name){
            filename = name;
        }

        public void DeleteFile(List<string> fileNames) {
            foreach (var fileName in fileNames){
                string fullPath = Path.Combine(getDataPath(), fileName);
                if (File.Exists(fullPath)) {
                    File.Delete(fullPath);
                }                
            }

        }

        private string getDataPath(){
            return Path.Combine(HostingEnvironment.ApplicationPhysicalPath,"App_Data");
        }

        private void SaveFile(Stream stream, FileStream fs) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            Debug.Assert(true);
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) {
                fs.Write(buffer, 0, bytesRead);
            }
            stream.Close();
            fs.Close();
        }
    }
}
